package com.wwj.core.pay.weixin.handler;

import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayMessage;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.wwj.core.wawa.entity.PlayerRecharge;
import com.wwj.core.wawa.service.IPlayerRechargeService;
import com.wwj.pay.service.handler.WxPayMessageHandler;

import javax.annotation.Resource;
import java.util.Map;

public class WaWaWxPayMessageHandler extends WxPayMessageHandler {

    @Resource
    private IPlayerRechargeService playerRechargeService;

    public WaWaWxPayMessageHandler(Integer payId) {
        super(payId);
    }

    @Override
    protected PayOutMessage business(PayMessage payMessage, Map<String, Object> context, PayService payService) {
        Map<String, Object> message = payMessage.getPayMessage();
        String result_code = (String) message.get("result_code");
        String out_trade_no = (String)message.get("out_trade_no");
        boolean success;
        try {
            PlayerRecharge playerRecharge = playerRechargeService.findByTradeNo(out_trade_no);
            success = playerRechargeService.dealRechargeComplete(playerRecharge.getPlayerId(), out_trade_no, "SUCCESS".equals(result_code), 1);
        } catch (Exception e){
            logger.error("微信支付完成，业务逻辑处理失败:", e);
            return  payService.getPayOutMessage("FAIL", "失败");
        }
        if ("SUCCESS".equals(result_code) && success) {
            return payService.getPayOutMessage("SUCCESS", "成功");
        } else {
            String err_code = (String)message.get("err_code");
            String err_code_des = (String)message.get("err_code_des");
            logger.error("微信交易失败[" + out_trade_no + "][" + err_code +"][" + err_code_des + "]");
            return  payService.getPayOutMessage("FAIL", "失败");
        }
    }
}
